/**
 * 
 */
package com.cfweb.controller.monit;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.cfweb.controller.BasicInfo;
import com.cfweb.util.DbUtil;
import com.cfweb.util.ExtJSResponse;

/**
 * @Title: monitTest.java
 * @Package com.cfweb.controller.alert
 * @Description: 监控测试
 * @author 龙立强
 * @date 2016年3月23日 下午8:58:58
 * @version V1.0
 */

@Service
@Path("/monit")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class MonitManagement {

	Logger logger = Logger.getLogger(BasicInfo.class);
	
	private String opentsdburl;
	
    @Value("${opentsdb}")
	public void setOpentsdburl(String opentsdburl) {
		this.opentsdburl = opentsdburl;
	}

    private String DEA;
	
    @Value("${DEA}")
	public void setDEA(String DEA) {
		this.DEA = DEA;
	}
    
	@Path("/monitAll")
	@GET
	public ExtJSResponse monitAll() throws Exception {
		
		 List< Map<String, String> > deaList = this.monitDEA();
//		 List< Map<String, String> > serviceList = this.monitService();
		 
//		 for(Map<String, String> map:serviceList){
//			 deaList.add(map);
//		 }
		 
		 return ExtJSResponse.successResWithData(deaList);
	}
	
	/**
	 * 监控通过service broker启动的虚拟机的资源情况
	 * @param opentsdburl
	 * @return
	 * @throws Exception
	 */
    public List<Map<String, String>> monitService() throws Exception {
		
    	List< Map<String, String> > returnList = new ArrayList<Map<String, String>>(); //最终返回值
    	
		//先从10.82.82.92数据源中获取到对应服务中每台机器的IP地址以及job名称	
		List<Map<String, String>> list = getServiceIpFromOtherDataSource();
		
		for(Map<String, String> map:list){
			
			String hostip = map.get("hostip");
			String jobname = map.get("jobname");
			Map<String, String> returnMap = new HashMap<String,String>();
			
			//拼接URL
			String memurl = "http://"+opentsdburl+":4242/q?start=10m-ago&m=avg:30s-max:system.mem.percent" + "%7B"
	        		+ "job="+jobname+",index=" +hostip+ "%7D" + "&ascii";
			String mempercent = getPercentByURL(memurl);	
			if(mempercent != null){
				returnMap.put("HardName", jobname);
				returnMap.put("IP", hostip);
				returnMap.put("memory", mempercent+"%");
			}
	        
		    String diskurl = "http://"+opentsdburl+":4242/q?start=10m-ago&m=avg:30s-max:system.disk.system.percent" + "%7B"
		    		+ "job="+jobname+",index=" +hostip+ "%7D" + "&ascii";
				
		        String diskpercent = getPercentByURL(diskurl);
		        if(diskpercent!=null){
		        	returnMap.put("disk", diskpercent+"%");
		    }
		        
		    
           returnList.add(map);
			
		}
		
		return returnList;

	}
	
    /***
     * 监控DEA的资源使用情况
     * @return
     * @throws Exception
     */
	public List<Map<String, String>> monitDEA() throws Exception {
		
		List< Map<String, String> > returnList = new ArrayList<Map<String, String>>(); //最终返回值
		
		String[] DEAurls = DEA.split(",");
		Map<String, String> map = new HashMap<String,String>();//构造返回值
		
		for(String DEAUrl:DEAurls){//循环遍历每一台组件
			
			//需要监控的信息：DEA容器的内存
			String memurl = "http://"+opentsdburl+":4242/q?start=10m-ago&m=avg:30s-max:system.mem.percent" + "%7B"
					+ "job=dea,index=" +DEAUrl+ "%7D" + "&ascii";
			//返回值格式：system.mem.percent 1459386028 9.100000381469727 index=10.10.10.133 job=dea role=core		
			String mempercent = getPercentByURL(memurl);	
			if(mempercent != null){
				map.put("HardName", "DEA");
		        map.put("IP", DEAUrl);
		        map.put("memory", mempercent+"%");
			}
	        
	        
	        String diskurl = "http://"+opentsdburl+":4242/q?start=10m-ago&m=avg:30s-max:system.disk.system.percent" + "%7B"
	        		+ "job=dea,index=" +DEAUrl+ "%7D" + "&ascii";
			//返回值格式：system.disk.system.percent 1459400416 10 index=10.10.10.133 job=dea role=core
			
	        String diskpercent = getPercentByURL(diskurl);
	        if(diskpercent!=null){
	        	map.put("disk", diskpercent+"%");
	        }
	        
	        returnList.add(map);
		}

        return returnList;
	}
	
	/**
	 * 通过url获取到对应的监控数据
	 * @param url
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	private String getPercentByURL(String url) throws ClientProtocolException, IOException {
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);

		HttpResponse response = httpClient.execute(httpGet);
		HttpEntity entity = response.getEntity();

		String content = EntityUtils.toString(entity, "UTF-8");
		if("".equals(content)) return null;
		String sub_content = content.substring(0, content.indexOf("index"));
		String[] str = sub_content.split(" ");
		double mempercent = Double.parseDouble(str[2]);

		DecimalFormat df = new DecimalFormat("#.00");
		return df.format(mempercent).toString();
	}




	/**
	 * 获取到service新建的服务的IP和对应的job名称，用来进行后面的查询
	 * @return
	 * @throws Exception
	 */
	private List<Map<String, String>> getServiceIpFromOtherDataSource() throws Exception{
		
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		
		Connection connection = DbUtil.getConnection();
		String sql = "select t1.hostip,t2.plan from sb_hosts t1 join sb_instances t2 on t1.service=t2.instance";
		PreparedStatement statement = connection.prepareStatement(sql);
		ResultSet rs = statement.executeQuery();

		
		while(rs.next()){

			Map<String, String> map = new HashMap<String,String>();
			map.put("hostip", rs.getString("hostip"));
			map.put("jobname", rs.getString("plan").split("-")[0]+"_vm");
			list.add(map);
		}
		return list;
	}
	
	

}
